package com.dt.app.controller.account;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dt.app.api.sys.service.SysExcelImportService;
import com.dt.app.api.sys.service.SysLoginLogService;
import com.dt.app.api.sys.service.SysOperatorLogService;
import com.dt.app.api.sys.service.SysUserService;
import com.dt.app.common.constant.ConstantCode;
import com.dt.app.common.response.ResultUtil;
import com.dt.app.common.service.AuthenticationInfoService;
import com.dt.app.common.utils.IpAddressUtils;
import com.dt.app.common.utils.ServletUtils;
import com.dt.app.exception.ExcelException;
import com.dt.app.modules.sys.entities.SysLoginLogEntity;
import com.dt.app.modules.sys.entities.SysOperatorLogEntity;
import com.dt.app.modules.sys.entities.SysUserEntity;
import com.dt.app.modules.sys.vo.request.*;
import com.dt.app.modules.sys.vo.response.SysUserPageResponse;
import com.dt.app.modules.sys.vo.response.SysUserResponse;
import com.dt.export.data.SysUserData;
import com.dt.export.utils.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DT
 * @date 2021/6/2 21:36
 */
@Api(tags = "系统用户信息API")
@RestController
@RequestMapping("api/v1/account")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOperatorLogService operatorLogService;
    @Autowired
    private SysExcelImportService sysExcelImportService;
    @Autowired
    private SysLoginLogService sysLoginLogService;
    @Autowired
    private AuthenticationInfoService authenticationInfoService;

    /*public SysUserController(SysUserService sysUserService, SysExcelImportService sysExcelImportService, SysOperatorLogService operatorLogService, SysLoginLogService sysLoginLogService, AuthenticationInfoService authenticationInfoService) {
        this.sysUserService = sysUserService;
        this.sysExcelImportService = sysExcelImportService;
        this.operatorLogService = operatorLogService;
        this.sysLoginLogService = sysLoginLogService;
        this.authenticationInfoService = authenticationInfoService;
    }*/

    @ApiOperation(value = "查询用户列表")
    @GetMapping("list")
    public ResultUtil<IPage<SysUserPageResponse>> list(SysUserPageRequest request){
        return sysUserService.queryList(request);
    }

    @PostMapping("save")
    @ApiOperation(value = "添加系统用户")
    public ResultUtil<SysUserSaveRequest> save(@RequestBody @Valid SysUserSaveRequest request){
        return sysUserService.saveUser(request);
    }

    @GetMapping("getById/{id}")
    @ApiOperation(value = "根据id查询用户")
    public ResultUtil<SysUserResponse> getById(@PathVariable Long id){
        return sysUserService.getUserById(id);
    }

    @PutMapping("update")
    @ApiOperation(value = "修改系统用户")
    public ResultUtil<SysUserSaveRequest> update(@RequestBody @Valid SysUserSaveRequest request){
        return sysUserService.updateUser(request);
    }

    @DeleteMapping("delete/{id}")
    @ApiOperation(value = "删除系统部门")
    public ResultUtil<SysUserEntity> delete(@PathVariable Long id){
        return sysUserService.deleteUser(id);
    }

    @PostMapping("updateUserStatus/{id}/{enabled}")
    @ApiOperation(value = "更新用户状态")
    public ResultUtil<?> updateUserStatus(@PathVariable Long id,@PathVariable Boolean enabled) {
        return sysUserService.updateUserStatus(id,enabled);
    }

    @PostMapping("export")
    @ApiOperation(value = "导出用户信息")
    public void export(HttpServletResponse response, @RequestBody List<String> columns) {
        List<SysUserEntity> entityList = this.sysUserService.list();
        if(!entityList.isEmpty()) {
            List<SysUserData> dataList = new ArrayList<>();
            for (SysUserEntity entity : entityList) {
                SysUserData userData = new SysUserData();
                userData.setId(entity.getId());
                userData.setAccountName(entity.getAccountName());
                userData.setUsername(entity.getUsername());
                userData.setEmail(entity.getEmail());
                userData.setIsAdmin(entity.getIsAdmin().equals(ConstantCode.STR_ONE) ? "是" : "否");
                userData.setDeptName(entity.getDeptName());
                userData.setCreateTime(entity.getCreateTime());
                dataList.add(userData);
            }
            try {
                ExcelUtils.exportExcel(response, ConstantCode.SYS_USER_TABLE_NAME, ConstantCode.SYS_USER_SHEET_NAME, SysUserData.class,dataList,columns);
            } catch (Exception e) {
                throw new ExcelException("表格导出异常");
            }
        }
    }

    @PostMapping(value = "import")
    @ApiOperation(value = "导入用户信息")
    public ResultUtil<?> importUserInfo() {
        // TODO 后续完善
        String fileName = "E:\\test.xlsx";
        try {
            ExcelUtils.importExcel(fileName, SysUserData.class,sysExcelImportService);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("导入失败:"+e.getMessage());
        }
        return ResultUtil.success();
    }

    @PostMapping(value = "updatePwd")
    @ApiOperation(value = "修改用户密码")
    public ResultUtil<Boolean> updatePwd(@RequestBody @Valid SysUserPwdRequest request){
        return sysUserService.updatePwd(request);
    }

    @PostMapping(value = "updatePwdByAdmin")
    @ApiOperation(value = "修改用户密码")
    public ResultUtil<?> updatePwdByAdmin(@RequestBody @Valid SysUserPwdRequest request){
        try{
            int rt = sysUserService.updatePwdByAdmin(request);
            if(rt<1)
                return ResultUtil.error();
            return ResultUtil.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @PostMapping(value = "updateAvatar")
    @ApiOperation(value = "修改用户头像")
    public ResultUtil<Boolean> updateAvatar(@RequestBody @Valid SysUserEntity request){
        return sysUserService.updateAvatar(request);
    }

    @GetMapping(value = "queryUserCountByDept")
    @ApiOperation(value = "根据部门统计用户")
    public ResultUtil<Map<String,Object>> queryUserCountByDept() {
        return sysUserService.queryUserCountByDept();
    }

    @GetMapping(value = "countUser")
    @ApiOperation(value = "统计系统用户总数")
    public ResultUtil<Integer> countUser() {
        Long count = sysUserService.count();
        return ResultUtil.success(count.intValue());
    }

    @ApiOperation(value = "查询操作日志列表")
    @GetMapping("queryOperatorLogList")
    public ResultUtil<IPage<SysOperatorLogEntity>> queryOperatorLogList(SysOperatorLogPageRequest request){
        return operatorLogService.queryOperatorLogList(request);
    }

    @ApiOperation(value = "删除操作日志")
    @DeleteMapping(value = "deleteOperatorLogById/{id}")
    public ResultUtil<?> deleteOperatorLogById(@PathVariable String id){
        return operatorLogService.deleteOperatorLogById(id);
    }

    @ApiOperation(value = "查询登录日志列表")
    @GetMapping("queryLoginLogList")
    public ResultUtil<IPage<SysLoginLogEntity>> queryLoginLogList(SysLoginLogPageRequest request){
        return sysLoginLogService.queryLoginLogList(request);
    }

    @ApiOperation(value = "删除登录日志")
    @DeleteMapping(value = "deleteLoginLogById/{id}")
    public ResultUtil<?> deleteLoginLogById(@PathVariable String id){
        return sysLoginLogService.deleteLoginLogById(id);
    }

    @ApiOperation(value = "记录退出日志")
    @PostMapping(value = "addLogoutInfo")
    public ResultUtil<?> addLogoutInfo(HttpServletRequest request){
        SysUserEntity sysUserEntity = (SysUserEntity) authenticationInfoService.getAuthentication();
        // 记录登录日志
        String ip = IpAddressUtils.getIpAddr(ServletUtils.getRequest());
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        this.sysLoginLogService.saveLoginLog(ConstantCode.SIGNOUT_STRING_KEY, sysUserEntity.getUsername(),userAgent,ip);
        return ResultUtil.success();
    }

    @ApiOperation(value = "批量删除操作日志")
    @DeleteMapping(value = "bathDeleteOperatorLogByIds")
    public ResultUtil<?> bathDeleteOperatorLogByIds(@RequestBody List<String> ids) {
        this.operatorLogService.removeByIds(ids);
        return ResultUtil.success();
    }

    @ApiOperation(value = "批量删除登录日志")
    @DeleteMapping(value = "bathDeleteLoginLogByIds")
    public ResultUtil<?> bathDeleteLoginLogByIds(@RequestBody List<String> ids) {
        this.sysLoginLogService.removeByIds(ids);
        return ResultUtil.success();
    }

}
